"""
场景(二分类问题):
    广告点击率
    是否为垃圾邮件
    是否患病
    金融诈骗
    虚假账号
"""
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report,roc_auc_score
from sklearn.externals import joblib

# 1.读取数据
# https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data
path = "./data/breast-cancer-wisconsin.data"
column_name = ['Sample code number','Clump Thickness','Uniformity of Cell Size','Uniformity of Cell Shape',
               'Marginal Adhesion','Single Epithelial Cell Size','Bare Nuclei','Bland Chromatin','Normal Nucleoli',
               'Mitoses','Class']
data = pd.read_csv(path, names=column_name)
# 2.缺失值处理
data = data.replace(to_replace='?', value=np.nan)
data.dropna(inplace=True)
# 3.划分数据集 iloc第一个参数代表所有的行, 第二个参数代表列从第二行到倒数第二行
x = data.iloc[:,1:-1]
y = data['Class']
x_train, x_test, y_train, y_test = train_test_split(x, y)
# 4.标准化
transfer = StandardScaler()
x_train = transfer.fit_transform(x_train)
x_test = transfer.transform(x_test)
# 4 预估器
estimator = LogisticRegression()
estimator.fit(x_train, y_train)
# 保存模型
# joblib.dump(estimator, 'logisticRegression.pkl')
# 加载模型
# estimator = joblib.load('logisticRegression.pkl')
# 5 得出模型
print("逻辑回归权重系数为: ", estimator.coef_)
print("逻辑回归偏置为: ", estimator.intercept_)
# 6 模型评估
y_predict = estimator.predict(x_test)
print("逻辑回归预测: ", y_predict)
print("比对真实值和预测值: ", y_test == y_predict)
error = estimator.score(x_test, y_test)
print("准确率: ", error)
# 准确率,召回率,可靠性,样本数量
report = classification_report(y_test, y_predict, labels=[2,4],target_names=["良性","恶性"])
# AUC指标,值在(0.5,1),越接近1越好,适合评价样本不平衡的分类器性能
# y_true: 每个样本的真实类别,必须为0(反例),1(正例)标记
y_true = np.where(y_test > 3, 1, 0)
auc = roc_auc_score(y_true, y_predict)
print(auc)


